import { motion, AnimatePresence } from "motion/react";
import { useEffect, useRef, useCallback, useState } from "react";
import { User, Bot } from "lucide-react";
import { Card } from "./ui/card";
import { MessageBubble } from "./MessageBubble";
import { TypingIndicator } from "./TypingIndicator";

export interface Message {
  id: string;
  text: string;
  sender: "user" | "assistant";
  timestamp: Date;
  status?: "sending" | "sent" | "delivered" | "error";
  reactions?: string[];
  isStreaming?: boolean;
}

interface MessageListProps {
  messages: Message[];
  editingMessageId: string | null;
  editedText: string;
  onCopyMessage: (text: string, messageId: string) => void;
  onEditMessage: (messageId: string) => void;
  onSaveEditedMessage: (messageId: string) => void;
  onCancelEdit: () => void;
  onAddReaction: (messageId: string, reaction: string) => void;
  onEditChange: (text: string) => void;
  onRegenerateMessage: (messageId: string) => void;
  currentAgentName?: string;
  currentAgentDescription?: string;
  copiedMessageId?: string | null;
}

export function MessageList({
  messages,
  editingMessageId,
  editedText,
  onCopyMessage,
  onEditMessage,
  onSaveEditedMessage,
  onCancelEdit,
  onAddReaction,
  onEditChange,
  onRegenerateMessage,
  currentAgentName,
  currentAgentDescription,
  copiedMessageId,
}: MessageListProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const lastMessageRef = useRef<HTMLDivElement>(null);
  const [isAutoScrolling, setIsAutoScrolling] = useState(false);

  // 智能滚动到底部
  const scrollToBottom = useCallback(() => {
    if (lastMessageRef.current && containerRef.current) {
      const container = containerRef.current;
      const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 200;

      if (isNearBottom || messages.length === 0) {
        setIsAutoScrolling(true);
        lastMessageRef.current.scrollIntoView({
          behavior: "smooth",
          block: "end"
        });

        setTimeout(() => setIsAutoScrolling(false), 100);
      }
    }
  }, [messages.length]);

  useEffect(() => {
    scrollToBottom();
  }, [messages, scrollToBottom]);

  // 处理滚动事件
  const handleScroll = useCallback(() => {
    if (containerRef.current && !isAutoScrolling) {
      const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
      const isAtBottom = scrollHeight - scrollTop - clientHeight < 50;

      // 可以在这里添加加载更多历史消息的逻辑
      if (!isAtBottom && scrollTop === 0) {
        // 顶部滚动，可以加载更多历史消息
      }
    }
  }, [isAutoScrolling]);

  // 欢迎界面
  if (messages.length === 0) {
    return (
      <div
        ref={containerRef}
        className="flex-1 overflow-y-auto"
        onScroll={handleScroll}
      >
        <motion.div
          initial={{ opacity: 0, y: 30 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.8, ease: "easeOut" }}
          className="h-full flex items-center justify-center p-4 md:p-8"
        >
          <div className="max-w-2xl w-full text-center">
            {/* 主要Logo和标题 */}
            <motion.div
              initial={{ scale: 0.8, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{
                delay: 0.2,
                duration: 0.6,
                type: "spring",
                stiffness: 200
              }}
              className="mb-6 md:mb-8"
            >
              <motion.div
                className="w-16 h-16 md:w-24 md:h-24 mx-auto mb-4 md:mb-6 bg-gradient-to-r from-blue-500 via-purple-500 to-pink-500 rounded-2xl md:rounded-3xl flex items-center justify-center shadow-xl md:shadow-2xl"
                animate={{
                  rotate: [0, 5, -5, 0],
                  scale: [1, 1.05, 1]
                }}
                transition={{
                  duration: 6,
                  repeat: Infinity,
                  ease: "easeInOut"
                }}
                whileHover={{ scale: 1.1, rotate: 10 }}
              >
                <Bot className="w-8 h-8 md:w-12 md:h-12 text-white" />
              </motion.div>

              <h1 className="text-2xl md:text-4xl lg:text-5xl font-bold bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 bg-clip-text text-transparent mb-3 md:mb-4">
                欢迎使用 {currentAgentName || "Iroh Rig"}
              </h1>

              <p className="text-base md:text-xl text-slate-600 dark:text-slate-400 mb-6 md:mb-8 leading-relaxed">
                {currentAgentDescription || "我是您的AI助手，随时准备帮助您解决问题、回答问题或进行创意协作。"}
              </p>
            </motion.div>

            {/* 功能特性卡片 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4, duration: 0.6 }}
              className="grid grid-cols-1 sm:grid-cols-3 gap-4 md:gap-6 mb-6 md:mb-8"
            >
              {[
                {
                  icon: "💬",
                  title: "智能对话",
                  description: "自然流畅的对话体验，理解上下文"
                },
                {
                  icon: "🚀",
                  title: "快速响应",
                  description: "实时流式响应，即时获得答案"
                },
                {
                  icon: "🛠️",
                  title: "多模态支持",
                  description: "文本、图像、代码等多种输入格式"
                }
              ].map((feature, index) => (
                <motion.div
                  key={feature.title}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.4 + index * 0.1, duration: 0.5 }}
                  whileHover={{ y: -5, scale: 1.02 }}
                  className="group"
                >
                  <Card className="p-4 md:p-6 bg-white/50 dark:bg-slate-800/50 backdrop-blur-sm border border-white/20 dark:border-slate-700/50 hover:shadow-lg transition-all duration-300">
                    <div className="text-2xl md:text-4xl mb-2 md:mb-4">{feature.icon}</div>
                    <h3 className="text-base md:text-lg font-semibold text-slate-900 dark:text-white mb-1 md:mb-2">
                      {feature.title}
                    </h3>
                    <p className="text-xs md:text-sm text-slate-600 dark:text-slate-400">
                      {feature.description}
                    </p>
                  </Card>
                </motion.div>
              ))}
            </motion.div>

            {/* 快速开始提示 */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.8, duration: 0.6 }}
              className="text-center"
            >
              <p className="text-slate-500 dark:text-slate-400 text-xs md:text-sm mb-3 md:mb-4">
                💡 尝试问一些问题，比如：
              </p>
              <div className="flex flex-wrap justify-center gap-2 md:gap-3">
                {[
                  "帮我写一个Python函数",
                  "解释一下量子计算",
                  "给我一些建议"
                ].map((suggestion, index) => (
                  <motion.button
                    key={suggestion}
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    transition={{ delay: 0.8 + index * 0.1, duration: 0.4 }}
                    whileHover={{ scale: 1.05, y: -2 }}
                    whileTap={{ scale: 0.95 }}
                    className="px-3 py-1.5 md:px-4 md:py-2 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 rounded-full text-xs md:text-sm hover:bg-blue-200 dark:hover:bg-blue-900/50 transition-colors"
                  >
                    {suggestion}
                  </motion.button>
                ))}
              </div>
            </motion.div>
          </div>
        </motion.div>
      </div>
    );
  }

  return (
    <div
      ref={containerRef}
      className="flex-1 overflow-y-auto"
      onScroll={handleScroll}
    >
      <div className="max-w-4xl mx-auto p-3 md:p-4 space-y-4 md:space-y-6">
        <AnimatePresence mode="wait">
          {messages.map((message, index) => {
            const prevMessage = messages[index - 1];
            const showAvatar = !prevMessage || prevMessage.sender !== message.sender;
            const isLastMessage = index === messages.length - 1;

            return (
              <motion.div
                key={message.id}
                ref={isLastMessage ? lastMessageRef : null}
                initial={{ opacity: 0, y: 30, scale: 0.95 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                exit={{ opacity: 0, y: -20, scale: 0.95 }}
                transition={{
                  duration: 0.5,
                  delay: Math.min(index * 0.05, 0.3),
                  type: "spring",
                  stiffness: 300,
                  damping: 25,
                }}
                className={`flex ${
                  message.sender === "user" ? "justify-end" : "justify-start"
                } group`}
              >
                <div className={`flex items-start space-x-2 md:space-x-3 max-w-full md:max-w-[85%] lg:max-w-[75%] ${
                  message.sender === "user" ? "flex-row-reverse space-x-reverse" : ""
                }`}>

                  {/* 头像 */}
                  {showAvatar && (
                    <motion.div
                      whileHover={{ scale: 1.1, rotate: message.sender === "user" ? -5 : 5 }}
                      className={`w-8 h-8 md:w-10 md:h-10 rounded-xl md:rounded-2xl flex items-center justify-center flex-shrink-0 shadow-md md:shadow-lg ${
                        message.sender === "user"
                          ? "bg-gradient-to-r from-blue-500 to-cyan-500"
                          : "bg-gradient-to-r from-purple-500 to-pink-500"
                      }`}
                    >
                      {message.sender === "user" ? (
                        <User className="w-4 h-4 md:w-5 md:h-5 text-white" />
                      ) : (
                        <Bot className="w-4 h-4 md:w-5 md:h-5 text-white" />
                      )}
                    </motion.div>
                  )}

                  {/* 消息内容 */}
                  <div className={`flex-1 ${!showAvatar ? message.sender === "user" ? "text-right" : "" : ""}`}>
                    <MessageBubble
                      message={message}
                      isEditing={editingMessageId === message.id}
                      editedText={editedText}
                      onCopyMessage={(text) => onCopyMessage(text, message.id)}
                      onEditMessage={onEditMessage}
                      onSaveEditedMessage={onSaveEditedMessage}
                      onCancelEdit={onCancelEdit}
                      onAddReaction={onAddReaction}
                      onEditChange={onEditChange}
                      onRegenerateMessage={onRegenerateMessage}
                      copiedMessageId={copiedMessageId}
                    />
                  </div>
                </div>
              </motion.div>
            );
          })}
        </AnimatePresence>

        {/* 流式消息的打字指示器 */}
        {messages.some(m => m.isStreaming) && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="flex justify-start"
          >
            <div className="flex items-start space-x-2 md:space-x-3 max-w-[75%]">
              <div className="w-8 h-8 md:w-10 md:h-10 rounded-xl md:rounded-2xl flex items-center justify-center flex-shrink-0 shadow-md md:shadow-lg bg-gradient-to-r from-purple-500 to-pink-500">
                <Bot className="w-4 h-4 md:w-5 md:h-5 text-white" />
              </div>
              <TypingIndicator />
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
}
